﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using WoSoft.PACS.Win.MyToolBars;
using WoSoft.PACS.Data.CheckData;
using DevComponents.DotNetBar.SuperGrid;
using WoSoft.PACS.Win.MyClass;
using WoSoft.PACS.Data.DataSourceData;
using WoSoft.PACS.Data.Models;
using WoSoft.PACS.Data.ModelsExt;
using System.IO;
using Microsoft.Reporting.WinForms;

namespace WoSoft.PACS.Win.Forms.TjfxForms
{
    public partial class FrmCheckReportSearch_LIS : FrmBase
    {

        DataSourceService dss = new DataSourceService();
        DataSourceModel dataSourceModel = null;

        public FrmCheckReportSearch_LIS()
        {
            InitializeComponent();
        }

        public FrmCheckReportSearch_LIS(RibbonBar ribar)
            : base(ribar)
        {
            InitializeComponent();
        }

        public override List<MyToolBars.OperationModel> Operations()
        {
            List<OperationModel> functionInfos = new List<OperationModel>();

            //检索数据
            var readButton = new OperationModel()
            {
                ID = Guid.NewGuid().ToString(),
                Name = "检索数据",
                Image = global::WoSoft.PACS.Win.Properties.Resources.scroll_view,
                ClickEvent = new EventHandler(ReadButton),
            };
            functionInfos.Add(readButton);

            //查看报告
            var viewReport = new OperationModel()
            {
                ID = Guid.NewGuid().ToString(),
                Name = "导出数据1",
                Image = global::WoSoft.PACS.Win.Properties.Resources.export1,
                ClickEvent = new EventHandler(OutPutButton1),
            };
            functionInfos.Add(viewReport);

            //导出数据
            var outPutButton = new OperationModel()
            {
                ID = Guid.NewGuid().ToString(),
                Name = "导出数据2",
                Image = global::WoSoft.PACS.Win.Properties.Resources.export1,
                ClickEvent = new EventHandler(OutPutButton2),
            };
            functionInfos.Add(outPutButton);

            //导出数据
            var PrintButton = new OperationModel()
            {
                ID = Guid.NewGuid().ToString(),
                Name = "报告查看",
                Image = global::WoSoft.PACS.Win.Properties.Resources.printer,
                ClickEvent = new EventHandler(outPrintButton),
            };
            functionInfos.Add(PrintButton);

            //刷新数据
            var refresh = new OperationModel()
            {
                ID = Guid.NewGuid().ToString(),
                Name = "刷新数据",
                Image = global::WoSoft.PACS.Win.Properties.Resources.refresh,
                ClickEvent = Refresh,
            };
            functionInfos.Add(refresh);

            //退出
            var exit = new OperationModel()
            {
                ID = Guid.NewGuid().ToString(),
                Name = "退出",
                Image = global::WoSoft.PACS.Win.Properties.Resources.exit,
                ClickEvent = ExitClick
            };
            functionInfos.Add(exit);

            return functionInfos;
        }


        //检索数据
        private void ReadButton(object sender, EventArgs e)
        {
            string fhz_id = "";//患者ID
            string fjy_zt = "";//检验状态
            string fhz_dept = "";//病人部门
            string fjy_yb_code = "";//样本号
            string fname = "";//姓名                
            string finstr_id = "";//仪器ID
            string fhz_type_id = "";//患者类别
            string fjy_date1 = this.dtStartTime.Value.ToString("yyyy-MM-dd");
            string fjy_date2 = this.dtEndTime.Value.ToString("yyyy-MM-dd");
            string fjy_dateWhere = "";
            fjy_yb_code = this.tb_ybh.Text;
            fname = this.tb_PatientName.Text;
            if (object.Equals(cbDepartment.SelectedValue, null))//病人部门
                fhz_dept = "";
            else
                fhz_dept = cbDepartment.SelectedValue.ToString();
            fhz_id = this.tb_PatientID.Text;
            fjy_zt = this.cbZT.Text;

            try
            {
                finstr_id = cbInstr.SelectedValue.ToString();
            }
            catch { }
            try
            {
                fhz_type_id = ((DevComponents.Editors.ComboItem)this.cbTypeID.SelectedItem).Value.ToString();
            }
            catch { }
            try
            {
                fjy_zt = ((DevComponents.Editors.ComboItem)this.cbZT.SelectedItem).Value.ToString();
            }
            catch { }

            if (cbInstr.Text == "" || cbInstr.Text == null)
                finstr_id = " (fjy_instr is not null) ";
            else
                finstr_id = " (fjy_instr='" + finstr_id + "') ";

            if (fhz_type_id == "")
                fhz_type_id = " and (fhz_type_id is not null)";
            else
                fhz_type_id = " and (fhz_type_id='" + fhz_type_id + "') ";

            fjy_dateWhere = " and (fjy_date>='" + fjy_date1 + "' and fjy_date<='" + fjy_date2 + "') ";

            if (fjy_yb_code == "" || fjy_yb_code == null)
                fjy_yb_code = " and (fjy_yb_code is not null) ";
            else
                fjy_yb_code = " and (fjy_yb_code='" + fjy_yb_code + "')";

            if (fname == "" || fname == null)
                fname = " and (fhz_name is not null) ";
            else
                fname = " and (fhz_name like '" + fname + "%')";

            if (fhz_dept == "" || fhz_dept == null)
                fhz_dept = " and (fhz_dept is not null) ";
            else
                fhz_dept = " and (fhz_dept='" + fhz_dept + "')";


            if (fhz_id == "" || fhz_id == null)
                fhz_id = " and (fhz_id is not null) ";
            else
                fhz_id = " and (fhz_id='" + fhz_id + "')";

            if (fjy_zt == "" || fjy_zt == null)
                fjy_zt = " and (fjy_zt is not null) ";
            else
                fjy_zt = " and (fjy_zt='" + fjy_zt + "')";

            string strWhere = finstr_id + fhz_type_id + fjy_dateWhere + fjy_yb_code + fname + fhz_dept + fhz_id + fjy_zt;
            dataGridViewReport.DataSource = DataSourceModelExtend.QueryTable(dataSourceModel, "select (SELECT top 1 z.fname FROM SAM_TYPE z WHERE (z.ftype = '性别' and z.fcode=t.fhz_sex)) as 性别,(SELECT top 1 z.fname FROM SAM_TYPE z WHERE (z.ftype = '年龄单位' and z.fcode=t.fhz_age_unit)) as 年龄单位,(SELECT top 1 z.fname FROM WWF_DEPT z WHERE (z.fdept_id=t.fhz_dept)) as 科室,(SELECT top 1 z.fname FROM SAM_SAMPLE_TYPE z WHERE (z.fsample_type_id=t.fjy_yb_type)) as 样本,(SELECT top 1 z.fname FROM WWF_PERSON z WHERE (z.fperson_id=t.fjy_user_id)) as 检验医师,(SELECT top 1 z.fname FROM WWF_PERSON z WHERE (z.fperson_id=t.fapply_user_id)) as 申请医师,(SELECT top 1 z.fname FROM WWF_PERSON z WHERE (z.fperson_id=t.fchenk_user_id)) as 核对医师,t.* FROM SAM_JY t where " + strWhere);
        }

        //导出数据1
        private void OutPutButton1(object sender, EventArgs e)
        {
            var rows = this.dataGridViewReport.Rows.Count;
            if (rows < 1) return;

            DataGridViewExport.DataGridviewShowToExcel(dataGridViewReport, false);
        }

        //导出数据2
        private void OutPutButton2(object sender, EventArgs e)
        {
            var rows = this.dataGridViewResult.Rows.Count;
            if (rows < 1) return;

            DataGridViewExport.DataGridviewShowToExcel(dataGridViewResult, false);
        }

        //报告查看
        private void outPrintButton(object sender, EventArgs e)
        {
            if (object.Equals(dataGridViewReport.CurrentRow, null)) return;
            string fjy_id = this.dataGridViewReport.CurrentRow.Cells["fjy_id"].Value.ToString();

            reportView.BringToFront();
        }

        //刷新数据
        private void Refresh(object sender, EventArgs e)
        {
            ReadButton(sender, e);
        }

        //退出
        private void ExitClick(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmCheckReportSearch_Load(object sender, EventArgs e)
        {
            dataSourceModel = dss.GetModelByID("检验");

            dataGridViewReport.AutoGenerateColumns = false;
            dataGridViewResult.AutoGenerateColumns = false;

            //加载部门
            cbDepartment.DataSource = DataSourceModelExtend.QueryTable(dataSourceModel, "select fdept_id,fp_id,fname 科室 from WWF_DEPT where fuse_flag=1");
            cbDepartment.DisplayMembers = "科室";
            cbDepartment.ValueMember = "fdept_id";
            cbDepartment.ParentFieldNames = "fdept_id,fp_id";
            cbDepartment.AdvTree.ExpandAll();
            cbDepartment.SelectedIndex = -1;

            cbInstr.DataSource = DataSourceModelExtend.QueryTable(dataSourceModel, "SELECT finstr_id,fname FROM sam_instr WHERE fuse_if=1 ORDER BY forder_by");
            cbInstr.ValueMember = "finstr_id";
            cbInstr.DisplayMember = "fname";
            cbInstr.SelectedIndex = -1;

            this.dtStartTime.Value = Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
            this.dtEndTime.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).AddDays(1).AddSeconds(-1);

            ReadButton(sender, e);
        }

        private void dataGridViewReport_SelectionChanged(object sender, EventArgs e)
        {
            if (object.Equals(dataGridViewReport.CurrentRow, null)) return;
            string fjy_id = this.dataGridViewReport.CurrentRow.Cells["fjy_id"].Value.ToString();

            bool exitsImg = false;

            DataTable dtReport = DataSourceModelExtend.QueryTable(dataSourceModel, "select (SELECT top 1 z.fname FROM SAM_TYPE z WHERE (z.ftype = '性别' and z.fcode=t.fhz_sex)) as 性别,(SELECT top 1 z.fname FROM SAM_TYPE z WHERE (z.ftype = '年龄单位' and z.fcode=t.fhz_age_unit)) as 年龄单位,(SELECT top 1 z.fname FROM WWF_DEPT z WHERE (z.fdept_id=t.fhz_dept)) as 科室,(SELECT top 1 z.fname FROM SAM_SAMPLE_TYPE z WHERE (z.fsample_type_id=t.fjy_yb_type)) as 样本,(SELECT top 1 z.fname FROM WWF_PERSON z WHERE (z.fperson_id=t.fjy_user_id)) as 检验医师,(SELECT top 1 z.fname FROM WWF_PERSON z WHERE (z.fperson_id=t.fapply_user_id)) as 申请医师,(SELECT top 1 z.fname FROM WWF_PERSON z WHERE (z.fperson_id=t.fchenk_user_id)) as 核对医师,t.*,dbo.f_GetOtherData(t.fjy_id) 备注 FROM SAM_JY t where t.fjy_id='" + fjy_id + "'");
            DataTable dtIMG = DataSourceModelExtend.QueryTable(dataSourceModel, "SELECT fimg_id,fjy_id,fimg_type,fimg,fimgname,forder_by,fremark FROM SAM_JY_IMG where fjy_id='" + fjy_id + "' order by forder_by");
            DataTable dtResult = DataSourceModelExtend.QueryTable(dataSourceModel, "select a.* from SAM_JY_RESULT a join SAM_ITEM b on a.fitem_id=b.fitem_id where a.fjy_id='" + fjy_id + "' order by b.fprint_num");

            dataGridViewResult.DataSource = dtResult;
            int intImgCount = dtIMG.Rows.Count;
            if (intImgCount > 0)
            {
                for (int iimg = 0; iimg < intImgCount; iimg++)
                {
                    switch (iimg)
                    {
                        case 0:
                            img1.Visible = true;
                            img2.Visible = false;
                            img3.Visible = false;
                            img4.Visible = false;
                            img5.Visible = false;
                            MemoryStream buf1 = new MemoryStream((byte[])dtIMG.Rows[iimg]["fimg"]);
                            Image image1 = Image.FromStream(buf1, true);
                            img1.Image = image1;
                            break;
                        case 1:
                            img2.Visible = true;
                            img3.Visible = false;
                            img4.Visible = false;
                            img5.Visible = false;
                            MemoryStream buf2 = new MemoryStream((byte[])dtIMG.Rows[iimg]["fimg"]);
                            Image image2 = Image.FromStream(buf2, true);
                            img2.Image = image2;
                            break;
                        case 2:
                            img3.Visible = true;
                            img4.Visible = false;
                            img5.Visible = false;
                            MemoryStream buf3 = new MemoryStream((byte[])dtIMG.Rows[iimg]["fimg"]);
                            Image image3 = Image.FromStream(buf3, true);
                            img3.Image = image3;
                            break;
                        case 3:
                            img4.Visible = true;
                            img5.Visible = false;
                            MemoryStream buf4 = new MemoryStream((byte[])dtIMG.Rows[iimg]["fimg"]);
                            Image image4 = Image.FromStream(buf4, true);
                            img4.Image = image4;
                            break;
                        case 4:
                            img5.Visible = true;
                            MemoryStream buf5 = new MemoryStream((byte[])dtIMG.Rows[iimg]["fimg"]);
                            Image image5 = Image.FromStream(buf5, true);
                            img5.Image = image5;
                            break;
                        default:
                            break;
                    }
                }
            }
            else
            {
                img1.Visible = false;
                img2.Visible = false;
                img3.Visible = false;
                img4.Visible = false;
                img5.Visible = false;
            }

            WoSoft_PACSDataSet.sam_jy_printDataTable dt_PrintDataTable = new WoSoft_PACSDataSet.sam_jy_printDataTable();
            int intResultCount = dtResult.Rows.Count;//结果记录数
            if (intResultCount > 0)
            {
                //---------结果值
                int int序号 = 0;
                for (int i = 0; i < intResultCount; i++)
                {
                    int序号 = i + 1;
                    DataRow printRow = dt_PrintDataTable.NewRow();
                    printRow["结果序号"] = int序号;
                    printRow["结果项目代码"] = dtResult.Rows[i]["fitem_code"];
                    printRow["结果项目名称"] = dtResult.Rows[i]["fitem_name"];
                    printRow["结果值"] = dtResult.Rows[i]["fvalue"];
                    printRow["结果项目单位"] = dtResult.Rows[i]["fitem_unit"];
                    printRow["结果标记"] = dtResult.Rows[i]["fitem_badge"];
                    printRow["结果参考值"] = dtResult.Rows[i]["fitem_ref"];
                    dt_PrintDataTable.Rows.Add(printRow);
                }

                //----------报告值
                dt_PrintDataTable.Rows[0]["医院名称"] = "重庆二郎医院";
                dt_PrintDataTable.Rows[0]["报表名称"] = "检验报告单";
                dt_PrintDataTable.Rows[0]["医院地址"] = "";
                dt_PrintDataTable.Rows[0]["检验实验室"] = "";
                dt_PrintDataTable.Rows[0]["医院联系电话"] = "";
                dt_PrintDataTable.Rows[0]["姓名"] = dtReport.Rows[0]["fhz_name"];
                dt_PrintDataTable.Rows[0]["性别"] = dtReport.Rows[0]["性别"];
                dt_PrintDataTable.Rows[0]["年龄"] = dtReport.Rows[0]["fhz_age"].ToString() == "0" ? "" : dtReport.Rows[0]["fhz_age"];
                dt_PrintDataTable.Rows[0]["年龄单位"] = dtReport.Rows[0]["年龄单位"];
                dt_PrintDataTable.Rows[0]["申请单号"] = dtReport.Rows[0]["fapply_id"];
                dt_PrintDataTable.Rows[0]["样本条码号"] = dtReport.Rows[0]["fapply_id"];
                dt_PrintDataTable.Rows[0]["样本号"] = dtReport.Rows[0]["fjy_yb_code"];
                //dtPrintDataTable.Rows[0]["样本类别"] = dtReport.Rows[0]["类型"];
                dt_PrintDataTable.Rows[0]["病人类型"] = dtReport.Rows[0]["fhz_type_id"];
                dt_PrintDataTable.Rows[0]["送检科室"] = dtReport.Rows[0]["科室"];
                dt_PrintDataTable.Rows[0]["申请者"] = dtReport.Rows[0]["申请医师"];
                dt_PrintDataTable.Rows[0]["检验者"] = dtReport.Rows[0]["检验医师"];
                dt_PrintDataTable.Rows[0]["审核者"] = dtReport.Rows[0]["核对医师"];

                dt_PrintDataTable.Rows[0]["床号"] = dtReport.Rows[0]["fhz_bed"];
                dt_PrintDataTable.Rows[0]["病人ID"] = dtReport.Rows[0]["fhz_id"];
                dt_PrintDataTable.Rows[0]["诊断"] = dtReport.Rows[0]["fjy_lczd"];

                dt_PrintDataTable.Rows[0]["申请时间"] = dtReport.Rows[0]["fapply_time"];
                dt_PrintDataTable.Rows[0]["采样时间"] = dtReport.Rows[0]["fsampling_time"];
                //dtPrintDataTable.Rows[0]["收样时间"] = dtReport.Rows[0]["fget_user_time"];

                dt_PrintDataTable.Rows[0]["检验时间"] = Convert.ToDateTime(dtReport.Rows[0]["freport_time"].ToString()).ToString("MM-dd HH:mm");
                dt_PrintDataTable.Rows[0]["审核时间"] = Convert.ToDateTime(dtReport.Rows[0]["fcheck_time"].ToString()).ToString("MM-dd HH:mm");
                try
                {
                    dt_PrintDataTable.Rows[0]["打印时间"] = Convert.ToDateTime(dtReport.Rows[0]["fprint_time"].ToString()).ToString("MM-dd HH:mm");
                }
                catch
                {
                    dt_PrintDataTable.Rows[0]["打印时间"] = DateTime.Now;
                }
                dt_PrintDataTable.Rows[0]["备注"] = dtReport.Rows[0]["fremark"];

                //----------图值
                if (dtIMG.Rows.Count > 0)
                {
                    exitsImg = true;
                    for (int iimg = 0; iimg < dtIMG.Rows.Count; iimg++)
                    {
                        switch (iimg)
                        {
                            case 0:
                                dt_PrintDataTable.Rows[0]["结果图1"] = dtIMG.Rows[iimg]["fimg"];
                                dt_PrintDataTable.Rows[0]["结果图1_名称"] = dtIMG.Rows[iimg]["fimgname"];
                                break;
                            case 1:
                                dt_PrintDataTable.Rows[0]["结果图2"] = dtIMG.Rows[iimg]["fimg"];
                                dt_PrintDataTable.Rows[0]["结果图2_名称"] = dtIMG.Rows[iimg]["fimgname"];
                                break;
                            case 2:
                                dt_PrintDataTable.Rows[0]["结果图3"] = dtIMG.Rows[iimg]["fimg"];
                                dt_PrintDataTable.Rows[0]["结果图3_名称"] = dtIMG.Rows[iimg]["fimgname"];
                                break;
                            case 3:
                                dt_PrintDataTable.Rows[0]["结果图4"] = dtIMG.Rows[iimg]["fimg"];
                                dt_PrintDataTable.Rows[0]["结果图4_名称"] = dtIMG.Rows[iimg]["fimgname"];
                                break;
                            case 4:
                                dt_PrintDataTable.Rows[0]["结果图5"] = dtIMG.Rows[iimg]["fimg"];
                                dt_PrintDataTable.Rows[0]["结果图5_名称"] = dtIMG.Rows[iimg]["fimgname"];
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            if (exitsImg)
                reportView.LocalReport.ReportEmbeddedResource = "WoSoft.PACS.Win.Forms.TjfxForms.ReportCom_NewImg.rdlc";
            else
                reportView.LocalReport.ReportEmbeddedResource = "WoSoft.PACS.Win.Forms.TjfxForms.ReportCom_NewAll.rdlc";
            reportView.LocalReport.EnableExternalImages = true;
            reportView.LocalReport.DataSources.Clear();
            reportView.LocalReport.DataSources.Add(new ReportDataSource("samDataSet_sam_jy_print", (DataTable)dt_PrintDataTable));

            this.reportView.RefreshReport();

            dataGridViewResult.BringToFront();
        }

        private void dataGridViewReport_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (object.Equals(null, dataGridViewReport.CurrentRow)) return;

            Clipboard.SetDataObject(dataGridViewReport.CurrentRow.Cells["备注"].Value);
        }

        private void dataGridViewReport_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (object.Equals(null, dataGridViewReport.CurrentRow)) return;

            Clipboard.SetDataObject(dataGridViewReport.CurrentRow.Cells["备注"].Value);
        }
    }
}
